package com.web.filters;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*@WebFilter(value = "/*")*/
public class AuthorFilter implements Filter {

    private FilterConfig filterConfig;

    /**
     * 初始化方法，获取过滤器的配置对象
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.定义和协议相关的请求和响应对象
        HttpServletRequest request ;
        HttpServletResponse response;
        HttpSession session;

        try{
            //2.把参数转换成协议相关的对象
            request = (HttpServletRequest)req;
            response = (HttpServletResponse)resp;
            session = request.getSession();
            //获取当前请求的url
            String url = request.getRequestURI();// /system/user
            if (url.endsWith(".js")||url.endsWith(".png")||
                    url.endsWith(".jpg")||url.endsWith("index.jsp")||
                    url.endsWith("login.jsp")||url.endsWith("unauthorized.jsp")){
                //放行
                chain.doFilter(request,response);
                return;
            }
            String queryString = request.getQueryString();//operation=main  或者operation=author&id=4028a1c34ec2e5c8014ec2ebf8430001
            if (queryString.endsWith("operation=login")||queryString.endsWith("operation=main")
                    ||queryString.endsWith("operation=logout")){
                //放行
                chain.doFilter(request,response);
                return;
            }
            //对请求的url进行处理
            //1.去除/
            url = url.substring(1);
            //2.截取&之前的数据
            int index = queryString.indexOf('&');
            if (index!=-1){
                //最终格式system/user?operation=main
                url = url+"?"+queryString.substring(0,index);
            }else {
                url = url+"?"+queryString;
            }
            //获取当前登录人的访问权限
            String authorStr = session.getAttribute("authorStr").toString();
            //对比看当前用户权限是否能访问
            if (authorStr.contains(url)){
                //如果有放行
                chain.doFilter(request,response);
                return;
            }else {
                //如果没有,跳转到非法访问页面
                response.sendRedirect(request.getContextPath()+"/unauthorized.jsp");
            }

            //6.放行
            chain.doFilter(request,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        //可以做一些清理操作
    }
}
